#! python3
#! -*- coding:utf-8 -*-

import os, sys, subprocess, threading, time, random
import colorsys
#from PIL import Image
import subprocess
#import winsound
# import re, random

# def getScreen():
    # p = subprocess.Popen('adb shell wm size', shell=True, stdout=subprocess.PIPE)
    # out, err = p.communicate()
    
    # pa = re.compile(r"Physical size: (\d+)x(\d+)")
    # m = re.match(pa, 'Physical size: 1080x1920')

    # if m:
    #     print(m.group(1))
    # else:
    #     print('no match')


def ProgressBar(cur_page, total_page, total_time):
    sys.stdout.write(' '*50 + '\r')

    i = 0
    per_time = total_time / 50
    while i <= 50:
        sys.stdout.write('(' + str(cur_page) + '/' + str(total_page) + ')[' + '='*i + ('>' if i < 50 else '') + (50-i-1)*'-' + '] ' + str(int((per_time*i/total_time)*100)) + '%'+ ' '*(3-len(str(i))) +'\r')
        sys.stdout.flush()
        i+=1
        time.sleep(per_time)
        #time.sleep(0.01)

def tap(page, t=30):
    # 1080x2340
    width = 1080
    height = 2340 #1920
   
    i = 0
    while True:
        i += 1
        if i > page:
            break
        
        w = random.randint((width / 2)+300, width-100)
        h = random.randint(1500, height - 300)
        l = random.randint(200, 390)

        # print('点击位置：point(%d %d)' % (w, h))

        if l % 3 == 0:
            os.system('adb shell input tap %d %d' % (w, h))
        else:
            os.system('adb shell input swipe %d %d %d %d' % (w, h, w-l, h))
        # time.sleep(time)

        # 判断背景色
        #if get_bgcolor() == False:
        #    time = 0.3
        #else:
        #    time = random.randint(25, 38)
        time = random.randint(t-6, t+8)
        
        ProgressBar(i, page, time)
        # print('')

    #winsound.Beep(600, 300)
    #winsound.PlaySound('ALARM8', winsound.SND_ASYNC) #立即返回，支持异步播放

def get_bgcolor():
    os.system('adb shell screencap -p /sdcard/1.png')
    #os.system('adb pull /sdcard/1.png')
    subprocess.call('adb pull /sdcard/1.png', shell = True, stdin=subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE)
    #time.sleep(1)
    os.system('adb shell rm /sdcard/1.png')

    f = os.getcwd() + '/1.png'
    image = Image.open(f)

    #颜色模式转换，以便输出rgb颜色值
    image = image.convert('RGBA')
     
    #生成缩略图，减少计算量，减小cpu压力
    image.thumbnail((200, 200))
     
    max_score = 0
    dominant_color = None

    for count, (r, g, b, a) in image.getcolors(image.size[0] * image.size[1]):
        # 跳过纯黑色
        if a == 0:
            continue
         
        saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
        
        y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
        
        y = (y - 16.0) / (235 - 16)
         
        # 忽略高亮色
        if y > 0.9:
            continue
         
        # Calculate the score, preferring highly saturated colors.
        # Add 0.1 to the saturation so we don't completely ignore grayscale
        # colors by multiplying the count by zero, but still give them a low
        # weight.
        score = (saturation + 0.1) * count
         
        if score > max_score:
            max_score = score
            dominant_color = (r, g, b)

    return dominant_color == (201, 196, 179)


# 使用方法： py main.py -p 10 -t 30
if __name__ == '__main__':
    # sys.exit()
    # 读取当前进程ID，可以通过以下命令方式暂停/继续：pssuspend [-r: 继续运行] pid
    pid = os.getpid()
    print('当前PID: %s' % pid)

    dict = {};
    args = sys.argv[1:]
    i = 0
    while(i < len(args)):
        dict[args[i][1:]] = int(args[i+1])
        i+=2
    if(dict.__contains__('t') == False):
        dict['t'] = 30

    page = dict['p']
    while(True):
        tap(page, dict['t'])
        print('')
        r = input('是否继续？输入 0 退出；大于 0，则为继续点击的页数: ')
        if (r == '0'):
            sys.exit()
        page = int(r)
    # ProgressBar(1, 100, 30)

    #winsound.PlaySound('ALARM8', winsound.SND_ASYNC) #立即返回，支持异步播放
    print('\007')
